"""
字幕处理API蓝图
提供视频字幕添加、字幕格式化等功能
"""

from flask import Blueprint, request, jsonify, send_file, current_app
import os
import logging
from app.service.subtitle_service import SubtitleService
from app.tools.utils import get_safe_filename, validate_file_extension

# 创建字幕API蓝图
subtitle_bp = Blueprint('subtitle', __name__, url_prefix='/subtitle')

def allowed_file(filename, allowed_extensions):
    """检查文件格式是否允许"""
    return validate_file_extension(filename, allowed_extensions)

def get_subtitle_service():
    """获取字幕服务实例"""
    return SubtitleService(current_app.config['UPLOAD_FOLDER'], current_app.config['OUTPUT_FOLDER'])

@subtitle_bp.route('/format', methods=['POST'])
def format_subtitle():
    """格式化字幕文件"""
    try:
        if 'subtitle' not in request.files:
            return jsonify({'error': '没有上传字幕文件'}), 400
        
        subtitle_file = request.files['subtitle']
        max_chars = request.form.get('max_chars', 20, type=int)
        
        if subtitle_file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        if not allowed_file(subtitle_file.filename, current_app.config['ALLOWED_EXTENSIONS']):
            return jsonify({'error': '不支持的文件格式'}), 400
        
        # 保存上传的文件
        filename = get_safe_filename(subtitle_file.filename)
        subtitle_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        subtitle_file.save(subtitle_path)
        
        try:
            # 使用字幕工具进行格式化
            from app.tools.subtitle_tools import SubtitleTools
            subtitle_tools = SubtitleTools()
            formatted_content = subtitle_tools.format_srt_subtitle(subtitle_path, max_chars)
            
            # 保存格式化后的文件
            output_filename = f"formatted_{filename}"
            output_path = os.path.join(current_app.config['OUTPUT_FOLDER'], output_filename)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(formatted_content)
            
            # 清理临时文件
            os.remove(subtitle_path)
            
            return send_file(output_path, as_attachment=True, download_name=output_filename)
            
        except Exception as e:
            # 清理临时文件
            try:
                os.remove(subtitle_path)
            except:
                pass
            raise e
    
    except Exception as e:
        logging.error(f"字幕格式化失败: {e}")
        return jsonify({'error': str(e)}), 500

@subtitle_bp.route('/add', methods=['POST'])
def add_subtitle():
    """为视频添加字幕"""
    try:
        if 'video' not in request.files or 'subtitle' not in request.files:
            return jsonify({'error': '需要上传视频和字幕文件'}), 400
        
        video = request.files['video']
        subtitle = request.files['subtitle']
        
        if not allowed_file(video.filename, current_app.config['ALLOWED_EXTENSIONS']):
            return jsonify({'error': '不支持的视频格式'}), 400
        
        # 保存上传的文件
        video_path = os.path.join(current_app.config['UPLOAD_FOLDER'], get_safe_filename(video.filename))
        subtitle_path = os.path.join(current_app.config['UPLOAD_FOLDER'], get_safe_filename(subtitle.filename))
        
        video.save(video_path)
        subtitle.save(subtitle_path)
        
        # 添加字幕
        subtitle_service = get_subtitle_service()
        result = subtitle_service.add_subtitle_service(video_path, subtitle_path)
        if not result['success']:
            # 清理临时文件
            try:
                if os.path.exists(video_path):
                    os.remove(video_path)
                if os.path.exists(subtitle_path):
                    os.remove(subtitle_path)
            except:
                pass
            return jsonify({'error': result['error']}), 500
        
        output_path = result['output_path']
        
        # 清理临时文件
        try:
            os.remove(video_path)
            os.remove(subtitle_path)
        except Exception as e:
            logging.warning(f"清理临时文件失败: {e}")
        
        return send_file(output_path, as_attachment=True, download_name='video_with_subtitle.mp4')
    
    except Exception as e:
        logging.error(f"添加字幕失败: {e}")
        return jsonify({'error': str(e)}), 500 

@subtitle_bp.route('/apply', methods=['POST'])
def apply_subtitle():
    """应用字幕设置到视频"""
    try:
        if 'video' not in request.files:
            return jsonify({'error': '没有上传视频文件'}), 400
        
        if 'subtitle' not in request.files:
            return jsonify({'error': '没有上传字幕文件'}), 400
        
        video_file = request.files['video']
        subtitle_file = request.files['subtitle']
        
        if video_file.filename == '':
            return jsonify({'error': '没有选择视频文件'}), 400
        
        if subtitle_file.filename == '':
            return jsonify({'error': '没有选择字幕文件'}), 400
        
        if not allowed_file(video_file.filename, current_app.config['ALLOWED_EXTENSIONS']):
            return jsonify({'error': '不支持的视频格式'}), 400
        
        # 获取字幕设置信息
        subtitle_data = request.form.get('subtitle_data')
        if not subtitle_data:
            return jsonify({'error': '没有提供字幕设置信息'}), 400
        
        # 获取预览设置
        generate_preview = request.form.get('generate_preview', 'false').lower() == 'true'
        preview_duration = request.form.get('preview_duration', 10, type=int)  # 默认10秒
        
        try:
            import json
            subtitle_settings = json.loads(subtitle_data)
        except json.JSONDecodeError:
            return jsonify({'error': '字幕设置信息格式错误'}), 400
        
        # 保存上传的文件
        video_filename = get_safe_filename(video_file.filename)
        subtitle_filename = get_safe_filename(subtitle_file.filename)
        video_path = os.path.join(current_app.config['UPLOAD_FOLDER'], video_filename)
        subtitle_path = os.path.join(current_app.config['UPLOAD_FOLDER'], subtitle_filename)
        
        video_file.save(video_path)
        subtitle_file.save(subtitle_path)
        
        try:
            # 使用字幕服务应用字幕设置
            subtitle_service = get_subtitle_service()
            
            # 如果需要生成预览视频，将预览时长传递给服务
            if generate_preview:
                subtitle_settings['preview_duration'] = preview_duration
            
            result = subtitle_service.apply_subtitle_service(video_path, subtitle_path, subtitle_settings)
            
            if not result['success']:
                # 清理临时文件
                try:
                    if os.path.exists(video_path):
                        os.remove(video_path)
                    if os.path.exists(subtitle_path):
                        os.remove(subtitle_path)
                except:
                    pass
                return jsonify({'error': result['error']}), 500
            
            output_path = result['output_path']
            
            # 清理临时文件
            try:
                os.remove(video_path)
                os.remove(subtitle_path)
            except Exception as e:
                logging.warning(f"清理临时文件失败: {e}")
            
            # 直接返回视频文件
            return send_file(output_path, as_attachment=True, download_name='video_with_subtitle.mp4')
            
        except Exception as e:
            # 清理临时文件
            try:
                if os.path.exists(video_path):
                    os.remove(video_path)
                if os.path.exists(subtitle_path):
                    os.remove(subtitle_path)
            except:
                pass
            raise e
    
    except Exception as e:
        logging.error(f"应用字幕设置失败: {e}")
        return jsonify({'error': str(e)}), 500 